package io.dy.pool;

import io.dy.guarded_extend.GuardedContainer;

import java.util.concurrent.*;

/**
 * @author dmj
 * @date 2024年04月17日 下午5:46
 * 自定义线程池 + 线程池监控日志
 */
public class CustomThreadPoolExecutor {

    private static volatile ThreadPoolExecutor instance = null;

    private CustomThreadPoolExecutor(){}

    public static ThreadPoolExecutor getInstance(){
        if (instance == null) {
            synchronized (GuardedContainer.class){
                if(instance == null){
                    instance = createThreadPoolExecute();
                }
            }
        }
        return instance;
    }

    private final static ThreadFactory THREAD_FACTORY = (runnable) ->{
        Thread thread = new Thread(runnable);
        thread.setName("dy_custom_thread_" + thread.getId());
        return thread;
    };

    /**
     * 创建线程池
     * @return
     */
    private static ThreadPoolExecutor createThreadPoolExecute() {

        return new ThreadPoolExecutor(
                        //核心线程数
                        Runtime.getRuntime().availableProcessors() * 2,
                        //最大线程数
                        Runtime.getRuntime().availableProcessors() * 5,
                        //存活时间
                        10,
                        //存活时间单位
                        TimeUnit.SECONDS,
                        //等待队列
                        new ArrayBlockingQueue<>(200),
                        //线程工厂
                        THREAD_FACTORY,
                        //拒绝策略
                        new ThreadPoolExecutor.DiscardPolicy()){

            @Override
            protected void beforeExecute(Thread t, Runnable r) {
                System.out.println(t.getName() + "线程正在准备执行任务; 当前核心线程数:" + getCorePoolSize() +", 最大线程数:" + getMaximumPoolSize() + ", 当前线程池大小:" + getPoolSize()
                        + ", 活动线程数:" + getActiveCount() + ", 收到任务数:" + getTaskCount() + ", 已完成任务数:" + getCompletedTaskCount() + ", 等待中的任务数:" + getQueue().size());
                getLargestPoolSize();
            }

            @Override
            protected void afterExecute(Runnable r, Throwable t) {
//                System.out.println( "线程池中某一任务执行完成; 当前核心线程数:" + getCorePoolSize() +", 最大线程数:" + getMaximumPoolSize() + ", 当前线程池大小:" + getPoolSize()
//                        + ", 活动线程数:" + getActiveCount() + ", 收到任务数:" + getTaskCount() + ", 已完成任务数:" + getCompletedTaskCount() + ", 等待中的任务数:" + getQueue().size());
            }
        };
    }
}
